package com.caigou.service.impl;

import com.caigou.bean.cms.entity.AdConfig;
import com.caigou.bean.cms.entity.AdContract;
import com.caigou.bean.cms.entity.AdContractAdjunct;
import com.caigou.bean.cms.entity.AdOperationLog;
import com.caigou.bean.cms.param.AdContractParam;
import com.caigou.bean.exam.entity.Users;
import com.caigou.component.OSSComponent;
import com.caigou.component.SnowflakeComponent;
import com.caigou.constant.NewsConstant;
import com.caigou.enums.ResponseEnum;
import com.caigou.mapper.cms.AdContractMapper;
import com.caigou.pojo.AdContractExportList;
import com.caigou.pojo.AdContractInfo;
import com.caigou.pojo.AdContractList;
import com.caigou.service.*;
import com.caigou.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Slf4j
@Service("adContractService")
public class AdContractServiceImpl implements AdContractService {

    @Resource
    private AdContractMapper adContractMapper;
    @Resource
    private AdContractAdjunctService adContractAdjunctService;
    @Resource
    private AdContractSequenceService adContractSequenceService;
    @Resource
    private AdListService adListService;
    @Resource
    private AdOperationLogService adOperationLogService;
    @Resource
    private AdConfigService adConfigService;

    @Resource
    private SnowflakeComponent snowflakeComponent;
    @Resource
    private OSSComponent ossComponent;

    @Override
    public Result loadAdContractList(AdContractParam param) {
        PageHelper.startPage(param.getPage(), param.getSize());
        List<AdContractList> adContractList = adContractMapper.loadAdContractList(param);
        if (null != adContractList){
            adContractList.forEach(item -> item.setAdjunctCount(adContractAdjunctService.loadAdContractAdjunctCount(item.getId())));
        }
        PageInfo<AdContractList> list = new PageInfo<>(adContractList);
        return Result.success(list);
    }

    @Override
    public Result loadAdContractExportList(AdContractParam param) {
        List<AdContractExportList> list = adContractMapper.loadAdContractExportList(param);
        if (null != list){
            list.forEach(item -> {
                // 签约部门判定
                switch (item.getDepartment()){
                    case "1":
                        item.setDepartment("汽车采购顾问部");
                        break;
                    case "2":
                        item.setDepartment("IT采购顾问部");
                        break;
                    case "3":
                        item.setDepartment("供应商采购顾问部");
                        break;
                    case "4":
                        item.setDepartment("政府采购顾问部");
                        break;
                    case "5":
                        item.setDepartment("发行与品牌推广部");
                        break;
                    case "6":
                        item.setDepartment("市场与运营部");
                        break;
                    case "9":
                        item.setDepartment("其它部门");
                        break;
                }
                // 获取附件数量
                item.setAdjunctCount(adContractAdjunctService.loadAdContractAdjunctCount(item.getId()));
            });
        }
        return Result.success(list);
    }

    @Override
    public Result deleteAdContract(AdContractParam param, Users users) {
        if (adListService.loadPublicCountByContract(param.getId()) > 0) return Result.error(ResponseEnum.CONTRACT_IS_PUBLIC);
        AdContractInfo adContract = adContractMapper.loadAdContractInfo(param.getId());
        // 删除合同数据
        adContractMapper.deleteAdContract(param.getId());
        // 删除合同附件数据
        adContractAdjunctService.deleteAdContractAdjunct(param.getId());
        // 保存当前操作记录
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(2);
        current.setActionType("删除合同");
        current.setUserId(users.getUserid());
        current.setAdConfigId(0);
        current.setAdContractId(param.getId());
        current.setAdContractCode(adContract.getContractCode());
        adOperationLogService.saveOperationData(current);
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result loadAdContractSequence() {
        return adContractSequenceService.loadAdContractSequence();
    }

    @Override
    public Result uploadAdContractAdjunct(MultipartFile[] files) {
        //多文件上传
        int failCount = 0;//文件上传失败数量
        int successCount = 0;//文件上传成功数量
        int fileCount = files.length;
        String[] fileUrls = new String[fileCount];
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String fileUrl = uploadAttachment(file);
            log.info("上传第{}个文件，上传文件源文件{}，fileUrl={}", i, file.getOriginalFilename(), fileUrl);
            if (fileUrl == null) {
                failCount++;
            } else {
                successCount++;
            }
            fileUrls[i] = fileUrl;
        }
        if (failCount == 0) {
            return Result.success(fileUrls);
        } else {
            return Result.custom(420, successCount + "个文件上传成功" + "," + failCount + "个文件上传失败", fileUrls);
        }
    }

    @Override
    public Result saveAdContract(AdContractParam param, Users users) {
        // 查询当前序列参数是否正常
        int result = adContractSequenceService.lockAdContractSequenceExits(Integer.valueOf(param.getContractNumber()));
        if (result != 0) {
            return Result.error(ResponseEnum.AD_CONTRACT_NUMBER_ERROR);
        }
        // 锁定广告合同序号表
        adContractSequenceService.lockAdContractSequence();
        // 保存合同数据
        AdContract adContract = new AdContract();
        adContract.setPartyA(param.getPartyA());
        adContract.setPartyB(param.getPartyB());
        adContract.setDepartment(param.getDepartment());
        adContract.setPerson(param.getPerson());
        adContract.setContractCode(param.getContractCode());
        adContract.setContractName(param.getContractName());
        adContract.setContractProp(param.getContractProp());
        adContract.setContractYear(param.getContractYear());
        adContract.setContractNumber(param.getContractNumber());
        adContract.setContractInfo(param.getContractInfo());
        adContract.setStartTime(param.getStartTime());
        adContract.setEndTime(param.getEndTime());
        adContractMapper.saveAdContract(adContract);
        if (null != adContract.getId()){
            // 保存合同附件数据
            if (null != param.getAdContractAdjunctList() && param.getAdContractAdjunctList().size() > 0){
                param.getAdContractAdjunctList().forEach(item-> adContractAdjunctService.saveAdContractAdjunct(adContract.getId(),item.getAdjunctName(),item.getAdjunctUrl()));
            }
        }
        // 更新序列值
        adContractSequenceService.updateAdContractSequence();
        // 完成合同保存之后，解锁序列表
        adContractSequenceService.unLockAdContractSequence();
        // 保存当前操作记录
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(2);
        current.setActionType("创建合同");
        current.setUserId(users.getUserid());
        current.setAdConfigId(0);
        current.setAdContractId(adContract.getId());
        current.setAdContractCode(param.getContractCode());
        adOperationLogService.saveOperationData(current);
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result loadAdContractInfo(AdContractParam param) {
        AdContractInfo adContractInfo = adContractMapper.loadAdContractInfo(param.getId());
        if (null != adContractInfo){
            // 获取当前合同发布位置列表(预设、正在使用、历史都算)
            List<AdConfig> list = adConfigService.loadAdConfigListByContractRelease(param.getId());
            adContractInfo.setReleasePosition(list);
            // 获取合同附件数据
            List<AdContractAdjunct> adContractAdjunctList = adContractAdjunctService.loadAdContractAdjunctList(adContractInfo.getId());
            adContractInfo.setAdContractAdjunctList(adContractAdjunctList);
        }
        return Result.success(adContractInfo);
    }

    @Override
    public Result deleteAdContractAdjunct(AdContractParam param) {
        adContractAdjunctService.deleteAdContractAdjunctById(param.getId());
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result saveAdContractAdjunct(AdContractParam param) {
        adContractAdjunctService.saveAdContractAdjunct(param.getId(),param.getAdContractAdjunct().getAdjunctName(),param.getAdContractAdjunct().getAdjunctUrl());
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Result updateAdContract(AdContractParam param, Users users) {
        // 保存合同数据
        AdContract adContract = new AdContract();
        adContract.setId(param.getId());
        adContract.setPartyA(param.getPartyA());
        adContract.setPartyB(param.getPartyB());
        adContract.setDepartment(param.getDepartment());
        adContract.setPerson(param.getPerson());
        adContract.setContractCode(param.getContractCode());
        adContract.setContractName(param.getContractName());
        adContract.setContractProp(param.getContractProp());
//        adContract.setContractYear(param.getContractYear());
//        adContract.setContractNumber(param.getContractNumber());
        adContract.setContractInfo(param.getContractInfo());
        adContract.setStartTime(param.getStartTime());
        adContract.setEndTime(param.getEndTime());
        adContractMapper.updateAdContract(adContract);
        // 保存新上传的附件
        if (null != param.getAdContractAdjunctList() && param.getAdContractAdjunctList().size() > 0){
            param.getAdContractAdjunctList().forEach(item -> {
                if (item.getId() == -1){
                    adContractAdjunctService.saveAdContractAdjunct(param.getId(),item.getAdjunctName(),item.getAdjunctUrl());
                }
            });
        }

        // 保存当前操作记录
        AdOperationLog current = new AdOperationLog();
        current.setModuleType(2);
        current.setActionType("修改合同合同");
        current.setUserId(users.getUserid());
        current.setAdConfigId(0);
        current.setAdContractId(adContract.getId());
        current.setAdContractCode(param.getContractCode());
        adOperationLogService.saveOperationData(current);
        return Result.success(ResponseEnum.SUCCESS);
    }

    @Override
    public Integer loadAdContractExit(Integer contractId) {
        return adContractMapper.loadAdContractExit(contractId);
    }

    private String uploadAttachment(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String fileExtension = "";
            assert fileName != null;
            int idx = fileName.lastIndexOf(".");
            if (idx > 0) {
                fileExtension = fileName.substring(idx);
            } else {
                log.error("上传文件错误，没有扩展名, fileName={}", fileName);
                return null;
            }

            long snowflakeId = snowflakeComponent.getInstance().nextId();
            String newFileName = snowflakeId + fileExtension;
            InputStream originInputStream = file.getInputStream();
            String strSnowflakeId = String.valueOf(snowflakeId);
            int length = strSnowflakeId.length();
            String picFolder = NewsConstant.ATTACHMENT_ROOT + "/" + strSnowflakeId.substring(length - 4, length - 2) + "/" + strSnowflakeId.substring(length - 2, length) + "/";
            log.info("picFolder={}", picFolder);
            String fileUrl = ossComponent.uploadToOSS(originInputStream, fileName, newFileName, picFolder);
            log.info("上传附件保存地址={}", fileUrl);
            return fileUrl;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
